package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zzyl.constant.JwtConstants;
import com.zzyl.dto.AccessTokenResultDto;
import com.zzyl.dto.Code2sessionResultDto;
import com.zzyl.dto.PhoneNumberResultDto;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtProperties;
import com.zzyl.service.MemberService;
import com.zzyl.service.WxService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.LoginVo1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: Insight
 * @Description: TODO
 * @Date: 2024/6/9 12:17
 * @Version: 1.0
 */
@Slf4j
@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    WxService service;

    @Autowired
    MemberMapper mapper;
    @Autowired
    JwtProperties jwtProperties;

    @Override
    public LoginVo1 login(UserLoginRequestDto dto) {
        Code2sessionResultDto code2sessionResultDto = service.code2Session(dto.getCode());
        if (code2sessionResultDto.getErrcode() != null) {
            throw new BaseException(BasicEnum.WX_LOGIN_ERROR);
        }
        String openid = code2sessionResultDto.getOpenid();
        log.info("openid:{}", openid);
        // 根据openid查询数据库 判断是否是首次登陆
        Member member = mapper.seleltByOpenid(openid);
        // 如果用户信息不为空，说明老用户，生成token返回
        if (member != null) {
            return buildMemeberVo(member);
        }
        // 如果用户信息为空，说明是新用户
        // 首先调用wx的获取accesstoken的接口
        AccessTokenResultDto accessTokenResultDto = service.accessToken();
        if (accessTokenResultDto.getErrcode() != null) {
            throw new BaseException(BasicEnum.WX_LOGIN_ERROR);
        }
        log.info("access token：{}", accessTokenResultDto.getAccess_token());
        // 调用wx的获取手机号的接口
        PhoneNumberResultDto phoneNumber = service.getPhoneNumber(accessTokenResultDto.getAccess_token(), dto.getPhoneCode());
        if (!Objects.equals(phoneNumber.getErrcode(), 0)) {
            throw new BaseException(BasicEnum.WX_LOGIN_ERROR);
        }
        log.info("phone number：{}", phoneNumber.getPhone_info().getPurePhoneNumber());
        // 添加insert一条member数据
        Member insert = new Member();
        insert.setName(dto.getNickName());
        insert.setPhone(phoneNumber.getPhone_info().getPurePhoneNumber());
        insert.setOpen_id(openid);
        insert.setGender(0);
        mapper.insert(insert);
        // 生成token返回
        return buildMemeberVo(insert);
    }

    public LoginVo1 buildMemeberVo(Member member) {
        Map<String, Object> data = new HashMap<>();
        data.put(JwtConstants.MEMBER_ID, member.getId());
        data.put(JwtConstants.MEMBER_NAME, member.getName());
        String token = JwtUtil.createJWT(jwtProperties.getBase64EncodedSecretKey(), jwtProperties.getTtl(), data);
        LoginVo1 memeberVo = BeanUtil.copyProperties(member, LoginVo1.class);
        memeberVo.setToken(token);
        memeberVo.setNickName(member.getName());
        return memeberVo;
    }
}

